package com.zlll.winner.controller.mall;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zlll.winner.business.service.mall.IMallOrderService;
import com.zlll.winner.business.vo.mall.MallOrderVo;
import com.zlll.winner.common.BaseController;
import com.zlll.winner.enums.mall.MallEnum;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/mallOrder")
public class MallOrderController extends BaseController {
    @Reference
    private IMallOrderService orderService;

    @PostMapping("getPage")
    public Object getPage(@RequestBody JSONObject data) {
        Integer pageNo = data.getInteger("pageNo") == null ? 1 : data.getInteger("pageNo");
        Integer pageSize = data.getInteger("pageSize") == null ? 20 : data.getInteger("pageSize");
        String goodsName = data.getString("goodsName");
        String orderNo = data.getString("orderNo");
        String account = data.getString("account");
        Integer status = data.getInteger("status");

        Long startTime = data.getLong("startTime");
        Long endTime = data.getLong("endTime");
        return orderService.getMallOrderVoPage(account, pageSize, pageNo, goodsName, orderNo, status, startTime, endTime);
    }

    @PostMapping("cancelStatus")
    public Object cancelStatus(@RequestBody JSONObject data) {
        Long id = data.getLong("id");
        try {
            orderService.cancelStatus(id, getUserId());
        }catch (Exception e){
            Assert.notNull(null, "取消失败");

        }
        return true;
    }
    @PostMapping("get/{id}")
    public Object getMallOrderVoById(@PathVariable Long id){
        return orderService.getMallOrderVoById(id);
    }

    /**
     * 修改地址
     * @param data
     * @return
     */
    @PostMapping("updateReceivingInfo")
    public Object updateReceivingInfo(@RequestBody JSONObject data){
        Long id = data.getLong("id");
        String address = data.getString("address");
        String contact = data.getString("contact");
        String consignee = data.getString("consignee");

        return orderService.updateReceivingInfo(id,getUserId(),address,contact,consignee);
    }


    /**
     * 导出反馈信息
     */
    @GetMapping("export")
    public void getAvailable(@RequestParam String goodsName,
                             @RequestParam(required = false) String orderNo,
                             @RequestParam(required = false) String account,
                             @RequestParam(required = false) Long startTime,
                             @RequestParam(required = false) Long endTime,
                             @RequestParam(required = false) Integer status,
                             HttpServletResponse response) throws IOException {
        IPage<MallOrderVo> page = orderService.getMallOrderVoPage(account, 100000, 1, goodsName, orderNo, status, startTime, endTime);
        List<MallOrderVo> list = page.getRecords();
        createXLSFile(list,response);
    }


    /**
     * 导出list为xls文件
     * @param list
     * @param response
     * @throws IOException
     */
    private void createXLSFile(List<MallOrderVo> list, HttpServletResponse response) throws IOException {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("订单信息");
        // 手动设置列宽。第一个参数表示要为第几列设；，第二个参数表示列的宽度，n为列高的像素数。
        sheet.setColumnWidth(0,1790);
        sheet.setColumnWidth(1, 3570);
        sheet.setColumnWidth(2, 5570);
        sheet.setColumnWidth(3, 3570);
        sheet.setColumnWidth(4, 4570);
        sheet.setColumnWidth(5, 3570);
        sheet.setColumnWidth(6, 5570);
        sheet.setColumnWidth(7, 3570);
        sheet.setColumnWidth(8, 4570);
        sheet.setColumnWidth(9, 3570);
        // 创建第一行
        Row row = sheet.createRow(0);
        // 创建列（每行里的单元格）
        Cell cell = row.createCell(0);
        cell.setCellValue("序号");
        cell = row.createCell(1);
        cell.setCellValue("订单编号");
        cell = row.createCell(2);
        cell.setCellValue("用户账号");
        cell = row.createCell(3);
        cell.setCellValue("兑换模块");
        cell = row.createCell(4);
        cell.setCellValue("商品名称");
        cell = row.createCell(5);
        cell.setCellValue("数量");
        cell = row.createCell(6);
        cell.setCellValue("积分");
        cell = row.createCell(7);
        cell.setCellValue("当前状态");
        cell = row.createCell(8);
        cell.setCellValue("下单时间");
        cell = row.createCell(9);
        cell.setCellValue("收货人");
        cell = row.createCell(10);
        cell.setCellValue("联系电话");
        cell = row.createCell(11);
        cell.setCellValue("收货地址");

        for (short i = 0; i < list.size(); i++) {
            MallOrderVo mallOrderVo = list.get(i);
            // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
            // 创建一行，在页sheet上
            row = sheet.createRow(i + 1);
            // 在row行上创建一个方格
            cell = row.createCell(0);
            cell.setCellValue(i + 1);
            cell = row.createCell(1);
            cell.setCellValue(mallOrderVo.getOrderNo());
            cell = row.createCell(2);
            cell.setCellValue(mallOrderVo.getAccount());
            cell = row.createCell(3);
            cell.setCellValue(getSourceName(mallOrderVo.getSource()));
            cell = row.createCell(4);
            cell.setCellValue(mallOrderVo.getGoodsName());
            cell = row.createCell(5);
            cell.setCellValue(mallOrderVo.getNum());
            cell = row.createCell(6);
            cell.setCellValue(mallOrderVo.getIntegralNum());

            cell = row.createCell(7);
            cell.setCellValue(getStatusName(mallOrderVo.getStatus()));
            cell = row.createCell(8);
            cell.setCellValue(formatLongTime("yyyy-MM-dd HH:mm:ss",mallOrderVo.getCreateTime()));
            cell = row.createCell(9);
            cell.setCellValue(mallOrderVo.getConsignee());
            cell = row.createCell(10);
            cell.setCellValue(mallOrderVo.getContact());
            cell = row.createCell(11);
            cell.setCellValue(mallOrderVo.getAddress());
        }
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            InputStream is = new ByteArrayInputStream(os.toByteArray());
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" +
                    new String(("订单信息" + ".xls").getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            bos = new BufferedOutputStream(out);
            bis = new BufferedInputStream(is);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
        }
    }

    public String getSourceName(Integer source){
        if(source.equals(1)){
            return "秒杀";
        }else{
            return "星选";
        }
    }

    public String getStatusName(Integer status){
        if(status.equals(MallEnum.StatusEnum.NOTPAY.val())){
            return MallEnum.StatusEnum.NOTPAY.desc();
        }
        if(status.equals(MallEnum.StatusEnum.cancel.val())){
            return MallEnum.StatusEnum.cancel.desc();
        }
        if(status.equals(MallEnum.StatusEnum.fail.val())){
            return MallEnum.StatusEnum.fail.desc();
        }
        if(status.equals(MallEnum.StatusEnum.PAY.val())){
            return MallEnum.StatusEnum.PAY.desc();
        }
        return "";
    }

    public static String formatLongTime(String format, Long date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.format(new Date(date));
    }

}
